header{
package com.aote.expression.antlr;
import java.util.Map;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.aote.util.ComponentHelper;
}

class LogicExpression extends Parser;

options
{
	k=2;
}

tokens
{
	AND="and";
	OR="or";
}

{
	private boolean getBoolean(String sbool) {
    	if(sbool.equals("true")) {
    		return true;
    	}
    	return false;
    }
    
    private String getValue(HTMLBasicComponent comp,Map map,String ID) {
       if(map==null){
    	  return ComponentHelper.getAttribute(comp,ID);
    	}else{
    	  return (String)map.get(ID);
    	}
    }
    
    private String getStringValue(String str) {
    	int len = str.length();
    	return str.substring(1, len - 1);
    }
}

expression [HTMLBasicComponent comp,Map map]
	returns [boolean result=false] {
	boolean b;
}
	: result=comparator[comp,map] ((AND b=comparator[comp,map]){result = result && b;} | (OR b=comparator[comp,map]){result = result || b;})*
	;
	
comparator [HTMLBasicComponent comp,Map map]
	returns [boolean result=false] {
	String a, b;
}
	: a=item[comp,map] EQUAL b=item[comp,map] {result = a.equals(b);} 
	| a=item[comp,map] NOTEQUAL b=item[comp,map] {result=!a.equals(b);}
	| a=item[comp,map] GT b=item[comp,map] {
		result=Double.parseDouble(a)>Double.parseDouble(b);
	}
	| a=item[comp,map] GE b=item[comp,map] {
		result=Double.parseDouble(a)>=Double.parseDouble(b);
	}
	| a=item[comp,map] LT b=item[comp,map] {
		result=Double.parseDouble(a)<Double.parseDouble(b);
	}
	| a=item[comp,map] LE b=item[comp,map] {
		result=Double.parseDouble(a)<=Double.parseDouble(b);
	}
	;

item [HTMLBasicComponent comp,Map map]
	returns [String result=""]
	: v1:STRING {result = getStringValue(v1.getText());}
	| v2:ID {result = getValue(comp, map,v2.getText());}
	;

class LogicLexer extends Lexer; 
options
{
	filter=true;
	k=2;
}

WS: ' '
 	{$setType(Token.SKIP);} 
 	;

STRING
	: "\"" (~('\"' | '\u0080'..'\ufffe') | '\u0080'..'\ufffe')* "\"" 
	;

ID
	: ('a'..'z'|'A'..'Z')('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
	;

EQUAL
	: "="
	;

NOTEQUAL
	: "!="
	;

LT: '<';
GT: '>';
LE: "<=";
GE: ">=";
